package com.mall.order.mq.promo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mall.order.OrderPromoService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dto.CreateSeckillOrderRequest;
import com.mall.order.dto.CreateSeckillOrderResponse;
import lombok.SneakyThrows;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author 晓帆
 * @version 1.0
 **/
@Component
public class PromoOrderConsumer {
    @Reference(timeout = 4000,check = false)
    OrderPromoService orderPromoService;
    DefaultMQPushConsumer consumer;
    @PostConstruct
    public void init(){
        consumer=new DefaultMQPushConsumer("promo_order_consumer");
        consumer.setNamesrvAddr("127.0.0.1:9876");
        try {
            consumer.subscribe("create_promotion_order","*");
            consumer.setMessageListener(new MessageListenerConcurrently() {
                @SneakyThrows
                @Override
                public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                    System.out.println("消费者开始执行");
                    MessageExt messageExt = list.get(0);
                    byte[] body = messageExt.getBody();
                    String s = new String(body, 0, body.length, "utf-8");
                    CreateSeckillOrderRequest request = JSON.parseObject(s, CreateSeckillOrderRequest.class);
                    CreateSeckillOrderResponse response = orderPromoService.createPromoOrder(request);
                    //根据response的状态判断时候消费成功
                    if (OrderRetCode.SUCCESS.getCode().equals(response.getCode())){
                        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                    }
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
            });
            consumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

}
